package cn.xiaobai.core.service;

import cn.xiaobai.core.domain.config.ToolInfo;
import cn.xiaobai.core.domain.config.ToolsConfig;
import cn.xiaobai.core.repository.PluginDataFactory;
import cn.xiaobai.core.repository.PluginDataMapper;
import cn.xiaobai.enums.ToolState;
import com.mybatisflex.core.update.UpdateChain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 插件初始化服务
 *
 * @Author yangdaji
 * @Date 2023/12/11
 * @PackageName cn.xiaobai.core.service
 * @ClassName PluginInitService
 */
@Slf4j
@Component
public class PluginInitService implements InitializingBean {

    @Autowired
    private PluginDataFactory pluginDataFactory;

    @Autowired
    private PluginDataMapper pluginDataMapper;

    @Autowired
    private ToolManager toolManager;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("初始化数据中...");
        // 初始化所有工厂
        pluginDataFactory.init();
        List<ToolInfo> toolAll = pluginDataMapper.selectAll();
        toolManager.init(toolAll);
        // 构建所有工具配置
        List<ToolInfo> toolInfos = new ToolsConfig(toolAll).buildToolConf(pluginDataFactory);
        // 修改所有工具为停止
        updateAllToolState(toolInfos);
        log.info("数据初始化完毕!");
    }

    private void updateAllToolState(List<ToolInfo> toolInfos) {
        UpdateChain<ToolInfo> updateChain = new UpdateChain<>(pluginDataMapper);
        for (ToolInfo toolInfo : toolInfos) {
            updateChain.setRaw("tool_state", ToolState.STOP.getId())
                    .eq("id", toolInfo.getId()).update();
        }

    }
}
